# 硬盘
from lib.config.settings import settings
import os


class Disk:
    def process(self, func_name):
        if not settings.DEBUG:  # 测试环境
            BASE_DIR = settings.BASE_DIR
            path = os.path.join(BASE_DIR, r'files\disk.out')
            fp = open(r'%s' % path, 'r', encoding='utf-8')
            info = fp.read()
            return self.parse(info)

        content = func_name('sudo MegaCli  -PDList -aALL')
        return self.parse(content)

    def parse(self, content):
                              # 插槽           # 容量大小                                  # 型号
        grep_pattern = {'Slot Number': 'slot', 'Raw Size': 'capacity', 'Inquiry Data': 'model', 'PD Type': 'pd_type'}   # 采集的数据映射

        disk_list = []
        response = {}
        lis = content.split('\n\n\n\n')
        for line in lis:
            if len(line):
                disk_list.append(line)   # 总共多少个硬盘
        for disk in disk_list:
            s = disk.strip().split('\n')
            response_key = None
            tem = {}  # 每个硬盘的采集数据
            for item in s:
                if not len(item.strip()): continue
                if len(item.strip().split(':')) != 2:
                    continue
                k, v = item.strip().split(':')
                if k == 'Slot Number':
                    response_key = v
                if k in grep_pattern:
                    tem[grep_pattern[k]] = v.strip()
            response[response_key] = tem  # 以每个硬盘的卡槽为key值
        return response
